package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.results.ErrorCode;
import com.itheima.service.UserService;
import com.itheima.system.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void save(User user) {
        boolean save = userDao.save(user);
        if(!save){
            throw new BizException(ErrorCode.SQL_ERROR,"save");
        }
    }

    @Override
    public void update(User user) {
        boolean update = userDao.update(user);
        if(!update){
            throw new BizException(ErrorCode.SQL_ERROR,"update");
        }
    }

    @Override
    public void delete(Integer id) {
        boolean delete = userDao.delete(id);
        if(!delete){
            throw new BizException(ErrorCode.SQL_ERROR,"delete");
        }
    }

    @Override
    public User get(Integer id) {
        User user = userDao.get(id);
        if(user == null){
            throw new BizException(ErrorCode.DB_QUERY_NOT_EXIST,"id");
        }
        return user;
    }

    @Override
    public PageInfo<User> getAll(int page,int size) {
        PageHelper.startPage(page,size);
        List<User> all = userDao.getAll();
        return new PageInfo<User>(all);
    }

    @Override
    public User login(String userName, String password) {
        User user = userDao.getByUserNameAndPassword(userName, password);
        if(user == null){
            throw new BizException(ErrorCode.USERNAME_ERROR,"用户名或密码错误");
        }
        return user;
    }
}
